import {Component, OnInit, AfterViewInit, ElementRef, Renderer2, ViewChild, OnDestroy} from '@angular/core';
import {ApiService} from '@core/services/http/api.service';
import {ApesMessageService} from "@shared/apes/message";
import {CompanyModalComponent} from "../company-modal/company-modal.component";
import {AnalysisService} from "../analysis.service";
import {UserAuthService} from "@core/services/user-auth.service";
import {Router} from "@angular/router";

@Component({
  selector: 'apes-total-control',
  templateUrl: './total-control.component.html',
  styleUrls: ['./total-control.component.scss'],
})

export class TotalControlComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild(CompanyModalComponent,{static:true}) child: CompanyModalComponent;
  private timer;
  private timers;

  /** 时间相关 **/
  todayTimes: Date;
  dateTimes: any[] = [];
  months: Date;
  dateMonths: any[] = [];

  /** 脑袋汇总 **/
  headList: any[];
  titleData = {};

  leftHead = {};               // 今日到店报价
  rightHead = {};              // 今日报案跟踪

  chart: any;
  companyLocal = this.as.getLocalObj();
  companyData = [];
  company: any;
  userInfo = this.userAuthService.getUserInfoObj();
  keyNum: any = 0;
  clickTime: any;
  year:any;
  companyLogo: any;                               // 5e746d2839bf6200014e3b20
  logoTitle: any;
  host:any = window.location.host;                // test57-6060.jekunauto.cn
  // host:any = 'test57-6060.jekunauto.cn';                // test57-6060.jekunauto.cn

  constructor(private apiService: ApiService,
              private el: ElementRef,
              private renderer: Renderer2,
              private msg: ApesMessageService,
              private as: AnalysisService,
              private userAuthService: UserAuthService,
              private router: Router,) {
    if (this.companyLocal) {
      let company: any = this.companyLocal;
      let data = [];
      for (let item of company) {
        for (let list of item['array']) {
          data.push(list.id);
        }
      }
      this.company = this.as.unique(data);
    } else if (this.userInfo) {
    } else {
      this.router.navigateByUrl('/analysis/control/index');
    }

    let times = (1000 * 60) * 10;
    this.timer = setInterval(() => {
      this.leftHead = {};
      this.rightHead = {};
      this.titleData = {};
      this.getHeadTop();
      this.getPieOne();
      this.getTodayMonitor();
      this.getTodayTrack();
    }, times);

    this.timers = setInterval(() => {
      this.dateMonths = [];
      this.dateTimes = [];
      this.getMonths();
      this.getTodayTimes();
    }, 1000);
  }

  ngOnInit() {
    const date = new Date();
    this.year = date.getFullYear();
    this.as.getImges('如约车服1').then(value => {
      this.logoTitle = value;
      this.companyLogo = value ? 'https://'+this.host+'/fileserver/view/'+value : './assets/tmp/img/bi/swzx_02.png';
    });
    this.companyData = this.company;
    this.changeCompany(this.companyData);
  }

  changeCompany(e) {
    this.companyData = e;

    this.getHeadTop();
    this.headList = this.setHeadData();
    this.getTodayMonitor();
    this.getTodayTrack();
    this.getPieOne();
    this.initFocus();
  }

  ngAfterViewInit() {
    const content = document.querySelector('#Boxs');
    const _body = document.querySelector('body');
    if( _body.clientWidth > 1920) {
      let _zoom = _body.clientWidth / content.clientWidth;
      setTimeout(() => {
        this.renderer.setStyle(content, 'zoom', _zoom);
      }, 100);
    }
  }

  // 返回上一页
  goBack($event: any) {
    let key = $event.button;
    if (key === 2) {
      history.go(-1);
      return false;
    }
  }

  private $(id) {
    return document.getElementById(id);
  }

  // 获取焦点
  initFocus() {
    this.$('system').focus();
  }

  getFocus() {
  }

  getKey($event, click?: any) {
    $event.preventDefault();
    let key = $event.keyCode;
    if (click === 1) {
      key = 0;
    }

    if (key === 0) {
      if(this.keyNum > 0) {
        this.onDblClick();
      }else {
        this.onClick();
      }
    }

    this.initFocus();
  }

  getMonths() {
    this.months = new Date();
    this.dateMonths = [];
    let shijian = 0;
    let riqi = 1;
    let newTimes;
    let month = this.months.toTimeString();
    for (let i = 0, len = month.length; i < len; i++) {
      newTimes = month.slice(shijian, riqi);
      this.dateMonths.push(newTimes);
      shijian++;
      riqi++;
    }
    this.dateMonths = this.dateMonths.filter((value) => value !== ':');
  }

  getTodayTimes() {
    this.todayTimes = new Date();
    this.dateTimes = [];
    let shijian = 0;
    let riqi = 1;
    let newTimes;
    let todayTime = this.todayTimes.toISOString();
    for (let i = 0, len = todayTime.length; i < len; i++) {
      newTimes = todayTime.slice(shijian, riqi);
      this.dateTimes.push(newTimes);
      shijian++;
      riqi++;
    }
    this.dateTimes = this.dateTimes.filter((value) => value !== '-');
  }

  // 脑袋汇总
  getHeadTop() {
    let data = {'interfaceMethod': 'ipmBusinessStatementService.getSwxgxx', 'pdata': {'companyId': this.companyData}};
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        // debugger;
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.titleData = data;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  setHeadData() {
    return [
      {
        titleData: [
          {lable: '车险报价台次', feild: 'ZBJCL'},
          {lable: '车险订单', feild: 'CXDD'},
          {lable: '新 / 续', feild: 'XIN', filed: 'XU'},
          {lable: '车险订单金额', feild: 'DDJE'},
          {lable: '报案数', feild: 'JRXZBA'},
          {lable: '到店车流', feild: 'DDCL'},
          {lable: '新增定损数', feild: 'XZDSS'},
          {lable: '定损完成', feild: 'WCDS'},
          {lable: '定损金额', feild: 'DSJE'},
        ],
      },
    ];
  }

  leftData = [
    {
      api: 'ipmBusinessStatementService.getDDBJXX',
      title: '已报价未录入意向及未报价',
      tabWidth: '100%',
      titleList: [
        {lable: '门店', feild: 'MDMC', width: '14%'},
        {lable: '车牌', feild: 'CPHM', logo: 'TPLJ', width: '14%'},
        {lable: '接车人', feild: 'ZDR', width: '10%'},
        {lable: '接车时间', feild: 'ZDRQ_SJ', width: '14%'},
        {lable: '报价结果', feild: 'BJJG', width: '14%'},
        {lable: '到店时长', feild: 'JGTS', width: '14%'},
        {lable: '意向录入', feild: 'YXLR', width: '14%'},
      ],
    },
    {
      api: 'ipmBusinessStatementService.getBXGZ',
      title: '今日应跟踪(新/续)',
      key: 1,
      todayLeft: '应跟踪: ',
      todayCenter: '已跟踪: ',
      tabWidth: '100%',
      titleList: [
        {lable: '门店', feild: 'MDMC', width: '130px'},
        {lable: '应跟踪总数', feild: 'XINKGZ', filed: 'XUKGZ', width: '110px'},
        {lable: '已跟踪总数', feild: 'XINYGZ', filed: 'XUYGZ', width: '110px'},
      ],
    },
  ];

  leftBottmData = [
    {
      api: 'ipmBusinessStatementService.getDSFA',
      title: '定损方案制定',
      todayLeft: '待制单 ',
      todayCenter: ' /  已制单 ',
      key: 2,
      tabWidth: '100%',
      titleList: [
        {lable: '保险公司', feild: 'BXGSMC', width: '13%', photo: 'BXGSTB'},
        {lable: '车牌', feild: 'CPHM', logo: 'CLTB', width: '13%'},
        {lable: '所在基地', feild: 'JDMC', width: '14%'},
        {lable: '接车门店', feild: 'MDMC', width: '13%'},
        {lable: '节点', feild: 'JDXX', width: '24%'},
        {lable: '到店时长', feild: 'TIO', width: '10%'},
      ],
    },
    {
      api: 'ipmBusinessStatementService.getHSFA',
      title: '核损方案制定',
      todayLeft: '待制单 ',
      todayCenter: ' /  已制单 ',
      key: 2,
      tabWidth: '100%',
      titleList: [
        {lable: '保险公司', feild: 'BXGSMC', width: '13%', photo: 'BXGSTB'},
        {lable: '车牌', feild: 'CPHM', logo: 'CLTB', width: '13%'},
        {lable: '所在基地', feild: 'JDMC', width: '14%'},
        {lable: '接车门店', feild: 'MDMC', width: '13%'},
        {lable: '节点', feild: 'JDXX', width: '24%'},
        {lable: '到店时长', feild: 'TDOT', width: '10%'},
      ],
    },
  ];

  rightTopData = [
    {
      title: '今日商务报案跟踪',
      tabWidth: '100%',
      titleWidth: '38%',
      api: 'ipmBusinessStatementService.getSWBA',
      titleList: [
        {lable: '跟踪人', feild: 'GZR', width: '9%'},
        {lable: '已跟踪', feild: 'YGZ', width: '8%'},
        {lable: '待跟踪', feild: 'DGZ', width: '8%'},
        {lable: '已到店', feild: 'YDD', width: '8%'},
      ],
    },
    {
      title: '今日商务待跟踪超时明细',
      tabWidth: '100%',
      titleWidth: '59%',
      api: 'ipmBusinessStatementService.getSWWGZ',
      titleList: [
        {lable: '保险公司', feild: 'BXGSMC', width: '13%', photo: 'BXGSTB'},
        {lable: '车牌', feild: 'CPHM', logo: 'CLTB', width: '14%'},
        {lable: '跟踪人', feild: 'GZR', width: '11%'},
        {lable: '超时', feild: 'YGSC', width: '14%'},
      ],
    },
    {
      title: '今日门店报案跟踪',
      key: 3,
      todayLeft: '已跟踪 ',
      todayCenter: '  未跟踪 ',
      todayEnd: ' /  已到店 ',
      tabWidth: '100%',
      api: 'ipmBusinessStatementService.getMDWGZ',
      titleList: [
        {lable: '保险公司', feild: 'BXGSMC', width: '10%', photo: 'BXGSTB'},
        {lable: '车牌', feild: 'CPHM', logo: 'CLTB', width: '12%'},
        {lable: '门店', feild: 'MDMC', width: '13%'},
        {lable: '门店跟踪人', feild: 'MDGJR', width: '9%'},
        {lable: '商务跟进人', feild: 'GZR', width: '10%'},
        {lable: '已过时长', feild: 'YGSC', width: '14%'},
      ],
    }
  ];

  rightTable = [
    {
      title: '历史应跟踪',
      key: 4,
      tabWidth: '100%',
      todayLeft: '商务应跟踪 ',
      todayCenter: ' /  门店应跟踪 ',
      api: 'ipmBusinessStatementService.getLSYGZ',
      titleList: [
        {lable: '保险公司', feild: 'BXGSMC', width: '100px', photo: 'BXGSTB'},
        {lable: '车牌', feild: 'CPHM', logo: 'CLTB', width: '115px'},
        {lable: '门店', feild: 'MDMC', width: '120px'},
        {lable: '门店跟踪人', feild: 'GZR', width: '85px'},
        {lable: '间隔天数', feild: 'JGTS', width: '100px'},
        {lable: '已跟踪次数', feild: 'HFCS', width: '100px'},
      ],
    },
  ];

  rightBottom = [
    {
      api: 'ipmBusinessStatementService.getBYSGDS',
      title: '本月事故定损',
      key: 4,
      tabWidth: '100%',
      titleWidth: '38%',
      titleList: [
        {lable: '车险报案', feild: 'CXBA', width: '12%'},
        {lable: '人保', feild: 'RB', width: '10%'},
        {lable: '人寿', feild: 'RS', width: '10%'},
        {lable: '其他', feild: 'QT', width: '9%'},
      ],
    },
    {
      api: 'ipmBusinessStatementService.getBAGZRXX',
      title: '.',
      tabWidth: '100%',
      titleWidth: '23%',
      titleList: [
        {lable: '跟踪人', feild: 'GZR', width: '9%'},
        {lable: '定损金额', feild: 'DSJE', width: '10%'},
      ],
    },
    {
      api: 'ipmBusinessStatementService.getAJLXTJ',
      title: '.',
      tabWidth: '100%',
      titleWidth: '35%',
      titleList: [
        {lable: '案件类型', feild: 'AJLX', width: '11%'},
        {lable: '回店', feild: 'HD', width: '7%'},
        {lable: '失效', feild: 'SX', width: '7%'},
        {lable: '待跟踪', feild: 'DGZ', width: '9%'},
      ],
    },
  ];

  // 今日到店报价
  getTodayMonitor() {
    let data = {'interfaceMethod': 'ipmBusinessStatementService.getDDBJ', 'pdata': {'companyId': this.companyData}};
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        let result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.leftHead = data.array;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 今日报案跟踪
  getTodayTrack() {
    let data = {'interfaceMethod': 'ipmBusinessStatementService.getJRBAGZ', 'pdata': {'companyId': this.companyData}};
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        let result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.rightHead = data;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 绘制饼图
  getPie(data: any[], html: string, col1: string, col2: string, id: string) {
    let height: number;
    if( document.body.clientWidth < 1900 ) {
      height = 255;
    } else {
      height = 320;
    }
    this.chart = new G2.Chart({
      container: id,
      forceFit: true,
      height: height,
      animate: false,
    });
    this.chart.source(data, {});
    this.chart.coord('theta', {
      radius: 0.65,
      innerRadius: 0.83,
    });
    this.chart.guide().html({
      position: ['50%', '50%'],
      html: html,
      alignX: 'middle',
      alignY: 'middle',
    });
    this.chart.intervalStack().position('value').color('item', [col1, col2]);
    this.chart.tooltip(false);
    this.chart.legend(false);
    this.chart.render();
  }

  // 本月保险销售
  getPieOne() {
    let data = {'interfaceMethod': 'ipmBusinessStatementService.getBYCXXS', 'pdata': {'companyId': this.companyData}};
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        let result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            if (data.one.length !== 0) {
              const col1 = '#09A5F3';
              const col2 = '#F7BB0F';
              const id = 'mountNode';
              const html = `<div style="font-size: 14px; margin-left: 36px;width: 10em;">
                              <p style="margin: 0">新保: <span>${ data.one[0].value}</span></p>
                              <p style="margin: 0">续保: <span>${ data.one[1].value }</span></p>
                          </div>`;
              this.getPie(data.one, html, col1, col2, id);
            }

            if (data.two.length !== 0) {
              const col1 = '#DD2D11';
              const col2 = '#091849';
              const id = 'container';
              const html = `<div style="font-size: 14px; margin-left: 36px;width: 10em;">
                              <p style="margin: 0">报价: <span>${ data.two[0].value}</span></p>
                              <p style="margin: 0">成交: <span>${ data.two[1].value }</span></p>
                          </div>`;
              this.getPie(data.two, html, col1, col2, id);
            }
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  onClick() {
    clearTimeout(this.clickTime);
    this.keyNum++;
    this.clickTime = setTimeout(()=>{
      this.keyNum = 0;
      this.router.navigateByUrl('/analysis/control/index');
    },500);
  }

  onDblClick() {
    clearTimeout(this.clickTime);
    this.child.isVisible = true;
    this.keyNum = 0;
  }

  ngOnDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
    if (this.timers) {
      clearInterval(this.timers);
    }
  }

}
